package android_serialport_api;

import android.util.Log;

import java.io.IOException;
import java.io.InputStream;

public abstract class SerialPortReadThread extends Thread {
    private InputStream mInputStream;

    private byte[] mReadBuffer;

    public SerialPortReadThread(InputStream mInputStream) {
        this.mInputStream = mInputStream;
        this.mReadBuffer = new byte[1024];
    }

    public boolean isInterrupted = false;

    public void setInterrupted(boolean interrupted) {
        isInterrupted = interrupted;
    }

    @Override
    public void run() {

        while (!isInterrupted) {
            try {
                if (mInputStream == null) return;

                int size = mInputStream.read(mReadBuffer);
                if (size > 0) {
                    ComBean ComRecData = new ComBean(mReadBuffer, size);
                    onDataReceived(ComRecData.getbRec());
                }
                if(isInterrupted)return;
                Thread.sleep(50);//延时50ms 等待数据写入缓存区
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
    }

    public abstract void onDataReceived(byte[] readBytes);
}
